using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class EnemyHealth : MonoBehaviour
{
    public static Action<Enemy> OnEnemyKilled;//定义敌人被杀死委托事件
    public static Action<Enemy> OnEnemyHit;//定义敌人受伤委托事件
    [SerializeField, Header("血条预制体")] private GameObject healthBarPrefab;
    [SerializeField, Header("血条位置")] private Transform barPosition;
    [SerializeField, Header("初始生命值")] private float initialHealth = 10f;
    [SerializeField, Header("最大生命值")] private float maxHealth = 10f;

    public float CurrentHealth { get; set; }
    private Image _healthBar;
    private Enemy _enemy;
    private void Start()
    {
        CreateHealthBar();
        CurrentHealth = initialHealth;
        _enemy = GetComponent<Enemy>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            DealDamage(5f);
        }
        _healthBar.fillAmount = Mathf.Lerp(_healthBar.fillAmount, CurrentHealth / maxHealth, Time.deltaTime * 10f);
    }

    // 创建血条
    private void CreateHealthBar()
    {
        // 实例化血条预制体并设置位置为敌人的位置
        GameObject newBar = Instantiate(healthBarPrefab, barPosition.position, Quaternion.identity);

        // 设置血条的父物体为当前敌人，使血条随着敌人移动
        newBar.transform.SetParent(transform);

        EnemyHealthContainer container = newBar.GetComponent<EnemyHealthContainer>();

        _healthBar = container.FillAmountImage;
    }

    public void ResetHealth()
    {
        CurrentHealth = initialHealth;
        _healthBar.fillAmount = 1f;
    }

    public void DealDamage(float damage)
    {
        CurrentHealth -= damage;
        if (CurrentHealth <= 0)
        {
            CurrentHealth = 0;
            Die();
        }
        else
        {
            OnEnemyHit?.Invoke(_enemy);
        }
    }

    private void Die()
    {
        // ResetHealth();
        OnEnemyKilled?.Invoke(_enemy);
        // ObjectPooler.ReturnToPool(gameObject);
    }
}